<?php
namespace Users\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\Sql\Predicate;
use Zend\Db\Sql\Expression;

class UsersTable
{
    protected $tableGateway;
	protected $select;
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
		$this->select = new Select();
    }
	public function addUser($users,$regbyAdmin)
    {	
		$password=md5($users['password']);
		$data = array(
			'user_name' 	=> str_replace(' ', '',$users['inputUserName']), 	
			'email' 		=> $users['inputEmail'],  		
			'password' 		=> $password, 	
			'user_type_id'  => $users['user_type'],  	
			'updated_date' 	=> date('Y-m-d H:i:s'),   
			'added_date'	=> date('Y-m-d H:i:s'), 	
			'u_status' 		=> 1,
		);
		
		if($regbyAdmin=='admin'){
			$this->tableGateway->insert($data);
			return $this->tableGateway->lastInsertValue;	
		}else{
			$this->tableGateway->insert($data);
			return $this->tableGateway->lastInsertValue;
		}	
    }
	public function updateUser($users){
		$data = array(
			//'user_name' 	=> str_replace(' ', '',$users['inputUserName']), 	
			'user_name' 	=> $users['inputUserName'], 	
			'email' 		=> $users['inputEmail'],  		
			'updated_date' 	=> date('Y-m-d H:i:s'),   
		);	
		$updat_status=$this->tableGateway->update($data, array('user_id' => $users['hid_user_id']));
		return $updat_status;
	}	
	public function checkEmail($email){
		$select = $this->tableGateway->getSql()->select();			
		$select->where('email="'.$email.'"');	
		$resultSet = $this->tableGateway->selectWith($select);
		return $resultSet->current();		
	}
	public function checkLogin($user)
    {	
		$password=md5($user['password']);			
		$select = $this->tableGateway->getSql()->select();
		$select->where('email="'.$user['inputEmail'].'"');
		$select->where('password="'.$password.'"');
		$select->join('clf_user_type', 'clf_user_type.user_type_id=clf_users.user_type_id',array('*'),'left');
		$select->where('clf_users.u_status=1');
		$resultSet = $this->tableGateway->selectWith($select);		
        $row = $resultSet->current();		
        return $row;
	}
	
	public function checkadminLogin($admin,$user_type)
    {	
		$password=md5($admin['password']);		
		$select = $this->tableGateway->getSql()->select();
		$select->where('email="'.$admin['inputEmail'].'"');
		$select->where('password="'.$password.'"');
		$select->join('clf_user_type', 'clf_user_type.user_type_id=clf_users.user_type_id',array('*'),'left');
		if($user_type=='user'){
			$user='admin';
			$select->where('clf_user_type.user_type!="'.$user.'"');
		}else{
			$select->where('clf_user_type.user_type="'.$user_type.'"');
		}
		$select->where('clf_users.u_status=1');
		$resultSet = $this->tableGateway->selectWith($select);	
        $row = $resultSet->current();		
        return $row;
	}
	public function getuserDetailes($user_id){		
		$select = $this->tableGateway->getSql()->select();
		$select->join('clf_user_type', 'clf_user_type.user_type_id=clf_users.user_type_id',array('*'),'left');
		$select->join('clf_user_details', 'clf_user_details.user_id=clf_users.user_id',array('*'),'left');
		$select->where('clf_users.user_id="'.$user_id.'"');	
		$resultSet = $this->tableGateway->selectWith($select);	
		return $resultSet->current();				
	}
	public function getpassword($pwd,$userid){ 
		$pwd=md5($pwd);
		$select = $this->tableGateway->getSql()->select();
		$select->where('password="'.$pwd.'"');
		$select->where('user_id="'.$userid.'"');
		$resultSet = $this->tableGateway->selectWith($select);
		$row = $resultSet->count();			
		return $row;
	}
	public function changepwd($pwd,$userid){
		$password=md5($pwd);
		$data = array(
				'user_id'       =>$userid,
				'password'      =>$password,
				);
		$changepassword=$this->tableGateway->update($data, array('user_id' => $data['user_id']));
		return 	$changepassword;			
	}
	public function checkUniqueRecord($email){	
		 $select = $this->tableGateway->getSql()->select()			
			->where('email="'.$email.'"');					 
		$resultSet = $this->tableGateway->selectWith($select);			
		$row=$resultSet->count();	
		return $row;
	}
	public function getMembersByMailId($email){	
		 $select = $this->tableGateway->getSql()->select()			
			->where('email="'.$email.'"');					 
		$resultSet = $this->tableGateway->selectWith($select);		
		return $resultSet;
	}
	public function setPwd($userid,$token){
		$mtoken=md5($token);		
		$data = array(
				'user_id'       =>$userid,
				'password'      =>$mtoken,
				);
		$setNewpassword=$this->tableGateway->update($data, array('user_id' => $data['user_id']));
		return 	$setNewpassword;	
	}
	public function setUsername($userid,$username){
		$data = array(
				'user_id'       =>$userid,
				'username'      =>$username,
				'joindate'      =>date('Y-m-d H:i:s'),
				'last_login'      =>date('Y-m-d H:i:s'),
				);
		$setUsername=$this->tableGateway->update($data, array('user_id' => $data['user_id']));
		return 	$setUsername;	
	}
	public function setUsertype($userid,$user_type){
		$data = array(
				'user_id'       =>$userid,
				'user_type'      =>$user_type,
				);
		$setUsertype=$this->tableGateway->update($data, array('user_id' => $data['user_id']));
		return 	$setUsertype;	
	}	
	public function getAdminusersGrid($quickSearchType,$aColumns,$data,$paginated=false)
	{
		$select = $this->tableGateway->getSql()->select();
		
		// Search
		if(isset($data['sSearch'])){
			if($data['sSearch']!='0' && $data['sSearch']!='')
			{
				$select->where(array(
					new Predicate\PredicateSet(
						array(
						new Predicate\Like('username', '%'.$data['sSearch'].'%'),
						),
							Predicate\PredicateSet::COMBINED_BY_OR
					),
				));
			}
		}
		// End
		
		//users Type
		if($_SESSION['userType']=='user'){
			$user_type='user';
			$select->where('user_type="'.$user_type.'"');
		}else if($_SESSION['userType']=='publisher'){
			$select->where('user_type!="user"');
		}
		
		//end
		
		// Sort Order
		$sOrder="";
		if(isset($data['iSortCol_0']))
		{
			
			for($i=0;$i<intval($data['iSortingCols']);$i++)
			{
				if($data['bSortable_'.intval($data['iSortCol_'.$i])] == "true")
				{
					$sOrder.=$aColumns[intval($data['iSortCol_'.$i])]." ".$data['sSortDir_'.$i].",";
				}
			}
			$sOrder = substr_replace($sOrder,"", -1);
		}
		if($sOrder!=''){
			$select->order($sOrder);
		}
		// End
		
		// Pagination
		if(isset($data['iDisplayStart']) && $data['iDisplayLength'] != '-1')
		{
			$start=(int)$data['iDisplayStart'];
			$currentPage = (int)$data['iDisplayLength'];
			$resultsPerPage = (int) $currentPage;
			$select->order('user.user_id DESC')->limit($currentPage)->offset($start);
		}
		// End
		
		$resultSet = $this->tableGateway->selectWith($select);
		return $resultSet;
	}
	public function getuserlistsGrid($searchkey,$aColumns,$data,$user_type_id,$paginated=false)
	{
		$select = $this->tableGateway->getSql()->select();
		$select->join('clf_user_type', 'clf_users.user_type_id=clf_user_type.user_type_id',array('*'),'left');		
		if($user_type_id!=''){
			$select->where('clf_users.user_type_id="'.$user_type_id.'"');
		}else{
			$select->where('clf_user_type.user_type_id!=1');
		}
		// Search
		if(isset($data['sSearch'])){
			if($data['sSearch']!='0' && $data['sSearch']!='')
			{
				$select->where(array(
					new Predicate\PredicateSet(
						array(
						new Predicate\Like('clf_users.user_name', '%'.$data['sSearch'].'%'),
						),
							Predicate\PredicateSet::COMBINED_BY_OR
					),
				));
			}
		}
		// End		
		// Sort Order
		if(isset($data['iSortCol_0']))
		{
			$sOrder="";
			for($i=0;$i<intval($data['iSortingCols']);$i++)
			{
				if($data['bSortable_'.intval($data['iSortCol_'.$i])] == "true")
				{
					$sOrder.=$aColumns[intval($data['iSortCol_'.$i])]." ".$data['sSortDir_'.$i].",";
				}
			}
			$sOrder = substr_replace($sOrder,"", -1);
		}
		if($sOrder!=''){
			$select->order($sOrder);
		}
		// End		
		// Pagination
		if(isset($data['iDisplayStart']) && $data['iDisplayLength'] != '-1')
		{
			$start=(int)$data['iDisplayStart'];
			$currentPage = (int)$data['iDisplayLength'];
			$resultsPerPage = (int) $currentPage;
			$select->order('clf_users.user_id DESC')->limit($currentPage)->offset($start);
		}
		// End		
		$resultSet = $this->tableGateway->selectWith($select);
		return $resultSet;
	}
	public function changeStatus($userIds,$value)
	{
		$data = array(
			'u_status'       =>$value,
		);
		$updateStatus=$this->tableGateway->update($data,array('(user_id IN ('.$userIds.'))'));
		return 	$updateStatus;			
	}
	public function deleteUser($id)
    {
        $result=$this->tableGateway->delete(array('user_id' => $id));
		return  $result;
    }	
	public function getcount($data='')
	{
		$select = $this->tableGateway->getSql()->select();
		if(isset($data['sSearch'])){
			if($data['sSearch']!='0' && $data['sSearch']!='')
			{
				$select->where(array(
					new Predicate\PredicateSet(
						array(
						new Predicate\Like('user_name', '%'.$data['sSearch'].'%'),
						),
							Predicate\PredicateSet::COMBINED_BY_OR
					),
				));
			}
		}		
		$resultSet = $this->tableGateway->selectWith($select);		
		return $resultSet->count();
	}	
	public function updateUserByAdmin($id,$data)
    {
		$data = array(
				'user_id' 	=>$id,
				'user_type' =>$data,
				);
		$updateuserid=$this->tableGateway->update($data, array('user_id' => $id));
		return 	$updateuserid;	
	}
	public function getallusersemails()
	{
		$select = $this->tableGateway->getSql()->select();
		$select->join('clf_user_type', 'clf_users.user_type_id=clf_user_type.user_type_id',array('*'),'left');
		$select->where('clf_user_type.user_type_id=3');
		$resultSet = $this->tableGateway->selectWith($select);	
		return $resultSet;
	}
	public function getuserId($name){	
		 $select = $this->tableGateway->getSql()->select()			
			->where('username="'.$name.'"');					 
		$resultSet = $this->tableGateway->selectWith($select);		
		return $resultSet;
	}
	public function deleteUsers($ids){		
		$this->tableGateway->delete(array('(user.user_id IN ('.$ids.'))'));			
		return $this->tableGateway->lastInsertValue;	
	}
	public function updateJoindate($id){			
		$data = array(
			'joindate'  =>date('Y-m-d'),
		);
		$updateuserid=$this->tableGateway->update($data, array('user_id' => $id));
		return 	$updateuserid;			
	}
	public function updateState($id){			
		$data = array(
			'state'  =>1,
		);
		$updateuserid=$this->tableGateway->update($data, array('user_id' => $id));
		return 	$updateuserid;			
	}
	public function getallFranchisee(){
		$select = $this->tableGateway->getSql()->select()			
			->where('user_type_id="2"');					 
		$resultSet = $this->tableGateway->selectWith($select);		
		return $resultSet;
	}
	public function getAdminDeatils(){
		$select = $this->tableGateway->getSql()->select()			
			->where('user_type_id="1"');					 
		$resultSet = $this->tableGateway->selectWith($select);		
		return $resultSet->current();
	}	
}